package com.handu.luna.boss.controller;

import com.handu.luna.core.domain.promotion.*;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * Created by wangzailiang on 2014/6/20.
 */
@Controller
@RequestMapping("/promotion/postcard/*")
public class PostCardPromotionController extends BaseController {


    @RequestMapping()
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        String state = "";
        if(viewState != null) {
            state = viewState;
        }
        return createModel("/promotion/postcard/index")
                .add("postCardPromotionPage", context.getPostCardPromotionRepository().findAll(pageable))
                .add("viewState",state);
    }

    @RequestMapping(value = "initGrant/{postCardPromotionId}")
    public BossModel initGrant(@PathVariable Long postCardPromotionId) {

        @SuppressWarnings("unused")
		PostCardPromotion postCardPromotion = context.getPostCardPromotionRepository().findOne(postCardPromotionId);

        return getGrantModel(postCardPromotionId);
    }

    @RequestMapping(value = "grant",method = RequestMethod.POST)
    public BossModel grant(Long grantNum,Long postCardPromotionId,RedirectAttributes redirectAttributes) {

        new PostCard().save(postCardPromotionId,grantNum);
        redirectAttributes.addFlashAttribute("message", "成功发放包邮卡"+grantNum);
        return createModel("redirect:index");
    }

    @RequestMapping(value = "view/index/{postCardPromotionId}")
    public BossModel view(@PathVariable Long postCardPromotionId,String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        String state = "";
        if(viewState != null) {
            state = viewState;
        }
        return createModel("/promotion/postcard/view/index")
                .add("postCardPromotionId",postCardPromotionId)
                .add("postCardPage", new PostCard().findAllByPostCardPromotionId(postCardPromotionId,pageable))
                .add("viewState", state);
    }

    @RequestMapping(value = "export/{postCardPromotionId}")
    public BossModel export(@PathVariable Long postCardPromotionId,HttpServletResponse response) {

        PostCardPromotion postCardPromotion = context.getPostCardPromotionRepository().findOne(postCardPromotionId);

        HSSFWorkbook wb = new PostCard().getExcelModel(postCardPromotionId);

        //String  mimetype = "application/x-msdownload";
        String fileName = postCardPromotion.getName();
        //String inlineType = "attachment";
        try {
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1" ) + ".xls\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(value="add",method = RequestMethod.GET)
    public BossModel add() {

        PostCardPromotion postCardPromotion = new PostCardPromotion();

        return getEditModel(postCardPromotion);
    }

    @RequestMapping(value="edit/{id}",method = RequestMethod.GET)
    public BossModel edit(@PathVariable Long id) {

        PostCardPromotion postCardPromotion = context.getPostCardPromotionRepository().findOne(id);

        return getEditModel(postCardPromotion);
    }

    @RequestMapping(value="save",method = RequestMethod.POST)
    //@InitBinder(value = {"name","bonusPrice","limitPrice","grantType","grantStartDate","grantEndDate","useStartDate","useEndDate","remark","grantLimitPrice","goodsIds","useRanges"})
    public BossModel save(@Valid final PostCardPromotion postCardPromotion, final BindingResult bindingResult, RedirectAttributes redirectAttributes) {

        if(bindingResult.hasErrors()) {
            return getEditModel(postCardPromotion);
        }
        redirectAttributes.addFlashAttribute("message", postCardPromotion.getSucessFlashMessage());
        context.getPostCardPromotionRepository().save(postCardPromotion);
        return createModel("redirect:index");
    }

    @RequestMapping(value="delete",method= RequestMethod.POST)
    public BossModel delete(String viewState,Long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
        context.getPostCardPromotionRepository().delete(id);
        context.getPostCardRepository().deleteByPostCardPromotionId(id);
        return createModel("/promotion/postcard/postcardpromotion_table")
                .add("postCardPromotionPage",context.getPostCardPromotionRepository().findAll(pageable))
                .add("viewState",viewState);
    }

    @RequestMapping(value="deletePostCard",method= RequestMethod.POST)
    public BossModel deletePostCard(String viewState,Long id,Long postCardPromotionId,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
        new PostCard().delete(id,postCardPromotionId);
        return createModel("/promotion/postcard/view/postcard_table")
                .add("postCardPromotionId",postCardPromotionId)
                .add("postCardPage", new PostCard().findAllByPostCardPromotionId(postCardPromotionId,pageable))
                .add("viewState",viewState);
    }

    public BossModel getEditModel(PostCardPromotion postCardPromotion) {

        return createModel("/promotion/postcard/info")
                .add("postCardPromotion", postCardPromotion);
    }

    private BossModel getGrantModel(Long postCardPromotionId) {

        PostCardPromotion postCardPromotion = context.getPostCardPromotionRepository().findOne(postCardPromotionId);

        return createModel("promotion/postcard/grant/grant")
                .add("postCardPromotion",postCardPromotion);

    }

    public BossModel getViewModel() {

        return createModel("/promotion/coupon/view/index");
    }
}
